package com.inspur.dgov.bsp.system.runner;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.inspur.dgov.bsp.system.entity.PubConfig;
import com.inspur.dgov.bsp.system.entity.PubDict;
import com.inspur.dgov.bsp.system.service.PubConfigService;
import com.inspur.dgov.bsp.system.service.PubDictService;
import com.inspur.dgov.common.boot.operation.RedissonCollection;
import com.inspur.dgov.common.tool.constant.AppConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 系统启动预处理
 *
 * @Author chiyupei
 * @Date 20/3/28 下午2:53
 * @Version 1.0
 * @Description 系统启动预处理
 */
@Component
@Order(1)
public class SystemStartupRunner implements CommandLineRunner {

    @Autowired
    private RedissonCollection redissonCollection;

    @Autowired
    private PubConfigService pubConfigService;

    @Autowired
    private PubDictService pubDictService;

    /**
     * 初始化字典等到Redis中
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        //从数据库获取所有字典类别
        QueryWrapper<PubConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PubConfig::getStatus, AppConstant.DB_STATUS_NORMAL);
        List<PubConfig> configList = this.pubConfigService.list(queryWrapper);
        //循环字典类别获取字典项到redis中
        for (PubConfig config : configList) {
            String configCode = config.getCode();
            Long configId = config.getId();
            List<PubDict> dictRList = this.redissonCollection.getList(configCode);
            if (null != dictRList) {
                this.redissonCollection.deleteList(configCode);
            }
            QueryWrapper<PubDict> dictWrapper = new QueryWrapper<>();
            dictWrapper.lambda().eq(PubDict::getStatus, AppConstant.DB_STATUS_NORMAL)
                    .eq(PubDict::getConfigId, configId);
            List<PubDict> dictList = this.pubDictService.list(dictWrapper);
            this.redissonCollection.setListValues(configCode, dictList, Long.valueOf(60 * 60 * 12 * 1000));
        }
    }
}
